<script lang="ts" setup>
import { ref, computed } from 'vue'
import { useVbenModal } from '@vben/common-ui'
import { Button, message, Collapse, CollapsePanel, Dropdown, Menu, MenuItem, Upload } from 'ant-design-vue'
import { useAccessStore } from '@vben/stores'
import { getProcessPurchaseList } from '#/api/backend/processPurchase'
import { AntDownloadOutlined } from '@vben/icons'

const accessStore = useAccessStore()

// 弹窗数据
const modalData = ref<any>({})

// 下载链接
const downUrl = ref('')

// 上传的文件数据
const fileData = ref<any[]>([])

// 文件类型选项
const fileTypeOptions = ref<any[]>([])

// 获取环境变量
const apiUrl = import.meta.env.VITE_GLOB_API_URL || ''

// 获取上传文件的token
const customHeaders = {
  batoken: accessStore.accessToken ?? '',
  'X-Requested-With': 'XMLHttpRequest',
}

// 弹窗配置
const [FileModal, fileModalApi] = useVbenModal({
  class: 'w-4/5',
  appendToMain: true,
  showConfirmButton: false,
  showCancelButton: false,
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      modalData.value = fileModalApi.getData<Record<string, any>>()
      downUrl.value = ''
      fileData.value = []
      // 获取文件类型统计
      loadFileTypeOptions()
    }
  },
})

/**
 * 加载文件类型选项
 */
const loadFileTypeOptions = async () => {
  try {
    const res = await getProcessPurchaseList({
      page: 1,
      limit: 1,
      search: modalData.value.search || {},
      quick_search: modalData.value.quick_search || '',
      exportFilesType: 2, // 获取文件类型统计
    })

    if (res.fileTypeList && Array.isArray(res.fileTypeList)) {
      fileTypeOptions.value = res.fileTypeList.map((item: any) => ({
        label: item.type_name,
        value: item.type_name,
        count: item.count || 0,
      }))
    }
  } catch (error) {
    console.error('加载文件类型失败', error)
  }
}

/**
 * 处理导出附件下拉点击
 */
const handleExportFiles = async (menuInfo: any) => {
  const selectedType = menuInfo.key

  const hide = message.loading('正在导出附件...', 0)
  try {
    const res = await getProcessPurchaseList({
      page: 1,
      limit: 1,
      search: modalData.value.search || {},
      quick_search: modalData.value.quick_search || '',
      exportFilesType: 1, // 导出附件
      exportFilesScene: selectedType,
    })

    if (res.data) {
      downUrl.value = res.data
      message.success('导出成功，请点击下载按钮')
    } else {
      message.warning('没有可导出的附件')
    }
  } catch (error) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

/**
 * 下载附件
 */
const handleDownload = () => {
  if (downUrl.value) {
    window.open(downUrl.value)
  } else {
    message.warning('请先导出附件')
  }
}

/**
 * 上传配置
 */
const uploadProps = computed(() => {
  const selectedIds = modalData.value.selectedRows?.map((row: any) => row.id) || []
  
  return {
    name: 'file',
    action: `${apiUrl}/admin/ProcessPurchase/uploadFile`,
    headers: customHeaders,
    data: {
      ids: selectedIds,
    },
    showUploadList: true,
    multiple: true,
    beforeUpload: (file: File) => {
      // 校验文件大小 (50MB)
      const maxSize = 50 * 1024 * 1024
      if (file.size > maxSize) {
        message.error('文件大小不能超过50MB')
        return false
      }
      return true
    },
    onChange: (info: any) => {
      if (info.file.status === 'done') {
        if (info.file.response && info.file.response.code === 1) {
          message.success(`${info.file.name} 上传成功`)
          // 更新文件数据
          if (info.file.response.data) {
            fileData.value.push(info.file.response.data)
          }
        } else {
          message.error(info.file.response?.msg || `${info.file.name} 上传失败`)
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`)
      }
    },
  }
})

/**
 * 保存文件
 */
const handleSaveFiles = async () => {
  if (!modalData.value.selectedRows || modalData.value.selectedRows.length === 0) {
    message.warning('请先在列表中选择一条记录')
    return
  }

  if (modalData.value.selectedRows.length > 1) {
    message.warning('只能选择一条记录')
    return
  }

  if (fileData.value.length === 0) {
    message.warning('请先上传文件')
    return
  }

  const hide = message.loading('正在保存...', 0)
  try {
    // 调用保存接口
    // await saveFiles({
    //   scene: 'scm_process_purchase',
    //   relationId: modalData.value.selectedRows[0].id,
    //   file_data: fileData.value,
    // })
    message.success('保存成功')
    fileModalApi.close()
  } catch (error) {
    message.error('保存失败')
  } finally {
    hide()
  }
}

/**
 * 关闭弹窗
 */
const handleClose = () => {
  fileModalApi.close()
}
</script>

<template>
  <FileModal title="附件管理与导出">
    <Collapse :default-active-key="['1', '2']">
      <!-- 导出附件 -->
      <CollapsePanel key="1" header="导出外面筛选结果下-所有相关附件">
        <div class="space-x-2">
          <Dropdown v-if="fileTypeOptions.length > 0">
            <Button type="primary">
              导出附件
              <template #icon>
                <AntDownloadOutlined />
              </template>
            </Button>
            <template #overlay>
              <Menu @click="handleExportFiles">
                <MenuItem v-for="item in fileTypeOptions" :key="item.value">
                  {{ item.label }}({{ item.count }})
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
          <span v-else class="text-gray-500">暂无附件</span>

          <Button v-if="downUrl" type="primary" @click="handleDownload">
            点击下载
            <template #icon>
              <AntDownloadOutlined />
            </template>
          </Button>
        </div>
      </CollapsePanel>

      <!-- 附件上传 -->
      <CollapsePanel key="2" header="附件上传">
        <div class="space-y-4">
          <div class="text-sm text-gray-600 mb-2">
            <p>提示：请先在列表中选择一条记录，然后上传附件</p>
            <p v-if="modalData.selectedRows && modalData.selectedRows.length === 1" class="text-green-600 mt-1">
              当前选中：{{ modalData.selectedRows[0].sn || modalData.selectedRows[0].id }}
            </p>
            <p v-else-if="modalData.selectedRows && modalData.selectedRows.length > 1" class="text-red-600 mt-1">
              只能选择一条记录
            </p>
            <p v-else class="text-red-600 mt-1">
              未选择记录
            </p>
          </div>

          <Upload v-bind="uploadProps">
            <Button type="primary">
              选择文件上传
            </Button>
          </Upload>

          <div class="text-sm text-gray-500">
            支持文件类型：不限，大小限制50MB
          </div>
        </div>
      </CollapsePanel>
    </Collapse>

    <template #prepend-footer>
      <Button @click="handleClose">取消</Button>
      <Button 
        v-if="modalData.selectedRows && modalData.selectedRows.length === 1"
        type="primary" 
        @click="handleSaveFiles"
      >
        保存
      </Button>
    </template>
  </FileModal>
</template>

<style scoped>
:deep(.ant-collapse-header) {
  font-weight: 500;
}
</style>
